package internal

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"k9-panel/app/model"
	"k9-panel/app/query"
	"log"
)

type UserTokenService struct {
}

func (u UserTokenService) Query(ctx context.Context, token string) (*model.UserToken, error) {
	return query.UserToken.ReadDB().Where(query.UserToken.Value.Eq(token)).First()
}

func (u UserTokenService) List() ([]*model.UserToken, error) {
	//TODO implement me
	return query.UserToken.Find()
}

func (u UserTokenService) Delete(model *model.UserToken) (uint, error) {
	info, err := query.UserToken.
		Where(query.UserToken.ID.Eq(model.ID)).Limit(1).Delete()
	if err != nil {
		return 0, err
	}
	return uint(info.RowsAffected), nil
}

func (u UserTokenService) Update(model *model.UserToken) (uint, error) {
	log.Default().Printf("%+v", model)
	if model.ID == 0 {
		_, err := query.UserToken.Where(query.UserToken.Desc.Eq(model.Desc)).First()
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				panic("名称不能重复！")
			}
			return 0, err
		}

		model.Value = uuid.New().String()
		err = query.UserToken.Create(model)
		if err != nil {
			return 0, err
		}
		//TODO implement me
		return model.ID, nil
	} else {
		_, err := query.UserToken.Where(query.UserToken.ID.Eq(model.ID)).Updates(model)
		if err != nil {
			return 0, err
		}
		return model.ID, nil
	}

}
